<template>
  <a-modal width="600px" v-model:visible="visible" :title="title" @before-ok="onOk">
    <a-form ref="formRef" :model="form" size="medium" auto-label-width>
      <a-form-item label="类型" field="type" :rules="[{ required: true, message: '请选择类型' }]">
        <a-radio-group v-model="form.type">
          <a-radio :value="0">文字</a-radio>
          <a-radio :value="1">图片</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="关键词" field="keyword" :rules="[{ required: true, message: '请输入关键词' }]">
        <a-input placeholder="请输入关键词" v-model="form.keyword" allow-clear></a-input>
      </a-form-item>
      <a-form-item
        label="关键词回复"
        field="reply"
        :rules="[{ required: true, message: '请输入关键词回复' }]"
        v-if="form.type == 0"
      >
        <a-textarea placeholder="点击输入文字（500字以内）" v-model="form.reply" allow-clear />
      </a-form-item>
      <a-form-item
        label="关键词回复"
        field="reply"
        :rules="[{ required: true, message: '请输入关键词回复' }]"
        v-if="form.type == 1"
      >
        <MsUpload v-model="form.reply"></MsUpload>
      </a-form-item>
      <a-form-item field="sort" label="排序">
        <a-input-number
          v-model="form.sort"
          :style="{ width: '100px' }"
          placeholder="请输入"
          class="input-demo"
          :min="0"
          :max="100"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import { reactive, ref, provide, computed } from 'vue'
import { keywordUpdate, keywordCreate } from '@/apis'
import { reAssign } from '@/utils/common'
import { Message } from '@arco-design/web-vue'
defineOptions({ name: 'groupEdit' })
const emit = defineEmits(['getTableData'])
const title = computed(() => (form.createdAt ? '编辑' : '新增'))
const formRef = ref()
const visible = ref(false)
const form = reactive({
  type: 0,
  keyword: '',
  keywordId: '',
  reply: '',
  appId: '',
  createdAt: '',
  sort: 0
})

// 打开编辑框并回显表单值
const addOrEdit = (item) => {
  reAssign(form, item)
  form.appId = item.appId ? item.appId : 1
  form.type = item.type ? item.type : 0
  item && formRef.value?.validate()
  visible.value = true
}
const onOk = async () => {
  const validateResult = await formRef.value?.validate()
  if (validateResult) return false
  const api = form.createdAt ? keywordUpdate : keywordCreate
  await api(form)
  Message.success('操作成功')
  emit('getTableData')
  return true
}

defineExpose({ addOrEdit })
provide('formRef', formRef)
</script>
<style lang="scss" scoped>
.edit_wrap {
  height: 100%;
  overflow: hidden;
  margin: $margin;
  background: var(--color-bg-1);
  padding: $padding;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}
</style>
